<template>
  <el-form>
    <el-form-item>
      <el-upload
        style="border: 1px dashed #d9d9d9;"
        class="avatar-uploader"
        :action="uploadCoverUrl"
        :headers="uploadHeaders"
        :show-file-list="false"
        :on-success="handleCoverSuccess"
        :before-upload="beforeUpload"
      >
        <el-avatar
          v-if="userForm.avatar"
          size="large"
          :src="userForm.avatar"
        />
        <i v-else class="el-icon-plus avatar-uploader-icon" />
      </el-upload>
    </el-form-item>
    <el-form-item label="Name">
      <el-input v-model.trim="userForm.name" />
    </el-form-item>
    <el-form-item label="Email">
      <el-input v-model.trim="userForm.email" />
    </el-form-item>
    <el-form-item label="Phone">
      <el-input v-model.trim="userForm.phone" />
    </el-form-item>
    <el-form-item label="Sex">
      <el-radio-group v-model="userForm.sex">
        <el-radio label="男" value="男">男</el-radio>
        <el-radio label="女" value="女">女</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit">Update</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getToken } from '@/utils/auth'
import { updateUserInfo } from '@/api/user'

export default {
  props: {
    user: {
      type: Object,
      default: () => {
        return {
          name: '',
          email: '',
          phone: '',
          sex: '',
          avatar: ''
        }
      }
    }
  },
  data() {
    return {
      uploadCoverUrl: '/api/uploadfile/upload',
      uploadHeaders: {
        Authorization: `${getToken()}`
      },
      userForm: {
        name: '',
        email: '',
        sex: '',
        phone: '',
        avatar: ''
      }
    }
  },
  mounted() {
    this.userForm = this.$props.user
  },
  methods: {
    // 上传封面成功
    handleCoverSuccess(res) {
      this.user.avatar = res.url
    },
    // 上传前检查文件类型和大小
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isImage) {
        this.$message.error('只能上传图片文件')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB')
      }
      return isImage && isLt2M
    },
    async submit() {
      await updateUserInfo(this.userForm)
      this.$store.commit('SET_SEX', this.userForm.sex)
      this.$store.commit('SET_NAME', this.userForm.name)
      this.$store.commit('SET_AVATAR', this.userForm.avatar)
      this.$store.commit('SET_PHONE', this.userForm.phone)
      this.$store.commit('SET_EMAIL', this.userForm.email)
      this.$message({
        message: 'User information has been updated successfully',
        type: 'success',
        duration: 5 * 1000
      })
    }
  }
}
</script>
